package netty.simple.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.time.LocalTime;

/**
 * @ClassName MyTestWebSocketFrameHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/4/13 13:13
 * @Version 1.0
 **/

/*
    WebSocketFrame 表示一个文本帧
 */
public class MyTestWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        System.out.println("服务器接收的消息："+ msg.text());

        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间："+ LocalTime.now() +"|"+ msg.text() ));
    }


    //当web客户端连接后，就会触发
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

        //id() 表示唯一值  LongText 唯一值  ,hortText 不是唯一 有可能重复
        System.out.println("handlerAdded被调用--"+ctx.channel().id().asLongText());
        System.out.println("handlerAdded被调用--"+ctx.channel().id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved被调用--"+ctx.channel().id().asLongText());
    }


    //异常发生被调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生--"+cause.getMessage());
        ctx.channel().close();
    }
}
